package com.controller;

import com.entity.News;
import com.entity.Notice;
import com.util.DataSourceUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/index.html")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
        List<Notice> notices = new ArrayList<>();
        String sql="select * from Notices";
        try(Connection con = DataSourceUtils.getConnection();
            PreparedStatement ps=con.prepareStatement(sql);
            ResultSet rs= ps.executeQuery()
        )
        {
            while(rs.next())
            {
                Notice notice=new Notice(rs.getString("NID"),rs.getString("Title"),rs.getString("Content"),rs.getString("Author"),rs.getObject("Date", LocalDateTime.class),rs.getString("ImageURL"));
                notices.add(notice);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        req.setAttribute("notices",notices);
        List<News> newss= new ArrayList<>();
        String sql2="select * from Newss";
        try(Connection con = DataSourceUtils.getConnection();
            PreparedStatement ps=con.prepareStatement(sql2);
            ResultSet rs= ps.executeQuery()
        )
        {
            while(rs.next())
            {
                News news=new News(rs.getString("nid"),rs.getString("Title"),rs.getString("Content"),rs.getString("Author"), rs.getObject("PublishDate", LocalDateTime.class),rs.getString("ImageURL"));
                newss.add(news);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        req.setAttribute("newss",newss);
        req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
        resp.sendRedirect(req.getContextPath()+"/index.html");
    }
}
